import React, { useState } from 'react';
import { Accordion } from 'antd-mobile';
import classnames from 'classnames';
import './index.less';

interface CollapsePanelProps {
  className?: string;
  open?: boolean;
  /**
   * 受控
   */
  controlled?: boolean;

  openedText?: string;
  closedText?: string;
  title: string | JSX.Element;
  footer?: (data?: any) => JSX.Element;
}
const Index: React.FunctionComponent<CollapsePanelProps> = ({
  children,
  title,
  open,
  closedText,
  openedText,
  footer,
  controlled,
  className,
}) => {
  const [opended, setOpened] = useState(open);

  const header = (
    <div className="hr-collapse-header">
      {title}
      <span className="hr-collapse-header-extra">{opended ? openedText : closedText}</span>
    </div>
  );

  const handleChange = (data) => {
    if (data && data[0] === '0') {
      setOpened(true);
    } else {
      setOpened(false);
    }
  };
  const props = {
    defaultActiveKey: '0',
    className: 'hr-collapse-panel',
    onChange: handleChange,
  } as any;
  if (!open) {
    delete props.defaultActiveKey;
  }
  if (controlled) {
    if (open) {
      props.activeKey = '0';
    } else {
      props.activeKey = '1';
    }
  }

  return (
    <div className={classnames('hr-collapse', className)}>
      <Accordion {...props}>
        <Accordion.Panel header={header} key="0">
          {children}
        </Accordion.Panel>
      </Accordion>
      {typeof footer === 'function' && <div className="hr-collapse-footer">{footer()}</div>}
    </div>
  );
};
Index.defaultProps = {
  open: true,
  openedText: '收起',
  closedText: '展开',
  controlled: false,
};

export default Index;
